package com.hmall.cart.listener;

import com.hmall.api.client.CartClient;
import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderStatusListener {
    @Autowired
    private ICartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(value = "trade.topic", type = ExchangeTypes.TOPIC, durable = "true"),
            key = {"order.create"}
    ))
    public void listenOrderStatus(List<Long> itemIds, @Header("user-info")Long userId) {
        if (userId != null) {
            // 获取当前用户id
            UserContext.setUser(userId);
            cartService.removeByItemIds(itemIds);
            UserContext.removeUser();
        } else {
            // 处理缺少user-info头部的情况
            System.out.println("user-info header is missing.");
        }
    }
}
